﻿using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Threading;
using InnovaApp.Layers.EntitiesLayer;
namespace InnovaApp.Layers.DataLayer
{
	public partial class DataRepositories : IDisposable
    {
        private static class ObjectContextCache
        {
            static ObjectContextCache()
            {
                _contextCache = new Dictionary<Thread, WeakReference>();
            }

            private static Dictionary<Thread, WeakReference> _contextCache;

            public static ObjectContext GetContext()
            {
                ObjectContext _context = null;
                _context = new InnovaAppEntities();
                return _context;
            }

            private static void ClearCache()
            {
                List<Thread> _toRemove = new List<Thread>();
                foreach (Thread t in _contextCache.Keys)
                    if (!_contextCache[t].IsAlive)
                        _toRemove.Add(t);

                foreach (Thread t in _toRemove)
                    _contextCache.Remove(t);
            }
        }


        public DataRepositories()
        {
            _context = ObjectContextCache.GetContext();
        }

        bool _contextDisposed = false;

        ~DataRepositories()
        {
            if (!_contextDisposed)
                this.Dispose();
        }

        public void Dispose()
        {
            _contextDisposed = true;
            _context = null;
        }
    }
}
